﻿using Caliburn.Micro;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Windows;
using System.Windows.Input;
using 行情显示.KeyHelper;
using 行情显示.Views;
using 行情显示.数据中心.ViewModels;

namespace 行情显示
{
    public class Bootstrapper : BootstrapperBase
    {
        //private SimpleContainer container;

        public Bootstrapper()
        {
            Initialize();
        }

        protected override void Configure()
        {
            //container = new SimpleContainer();
            //container.Singleton<IWindowManager, WindowManager>()
            //         .Singleton<IEventAggregator, EventAggregator>();
            //container.PerRequest<MainWindowViewModel>();

            ViewLocator.AddNamespaceMapping("行情显示.数据中心.ViewModels", "行情显示.Views");

            SetupKey();
        }

        /// <summary>
        /// 安装键盘触发事件
        ///  cal:Message.Attach="[Key Enter] = [EnterPressed]; [Gesture Ctrl+Enter] = [CtrlEnterPressed]"
        /// </summary>
        private void SetupKey()
        {
            var defaultCreateTrigger = Parser.CreateTrigger;
            Parser.CreateTrigger = (target, triggerText) =>
            {
                if (triggerText == null)
                {
                    return defaultCreateTrigger(target, null);
                }

                var triggerDetail = triggerText
                    .Replace("[", string.Empty)
                    .Replace("]", string.Empty);

                var splits = triggerDetail.Split((char[])null, StringSplitOptions.RemoveEmptyEntries);

                switch (splits[0])
                {
                    case "Key":
                        var key = (Key)Enum.Parse(typeof(Key), splits[1], true);
                        return new KeyTrigger { Key = key };

                    case "Gesture":
                        var mkg = (MultiKeyGesture)(new MultiKeyGestureConverter()).ConvertFrom(splits[1]);
                        return new KeyTrigger { Modifiers = mkg.KeySequences[0].Modifiers, Key = mkg.KeySequences[0].Keys[0] };
                }

                return defaultCreateTrigger(target, triggerText);
            };
        }

        protected override IEnumerable<Assembly> SelectAssemblies()
        {
            yield return typeof(MainWindowView).Assembly;
            yield return typeof(MainWindowViewModel).Assembly;
        }

        protected override void OnStartup(object sender, StartupEventArgs e)
        {
            DisplayRootViewFor<MainWindowViewModel>();
        }

        //protected override object GetInstance(Type service, string key)
        //{
        //    return container.GetInstance(service, key);
        //}

        //protected override IEnumerable<object> GetAllInstances(Type service)
        //{
        //    return container.GetAllInstances(service);
        //}

        //protected override void BuildUp(object instance)
        //{
        //    container.BuildUp(instance);
        //}
    }
}
